package com.treasure.mall.zbqmallmanager.controller.order;

import com.treasure.mall.biz.base.UserDetails;
import com.treasure.mall.biz.dto.condition.BizOrderCondition;
import com.treasure.mall.biz.dto.condition.OrderSearchCondition;
import com.treasure.mall.biz.dto.order.DeliverDTO;
import com.treasure.mall.biz.entity.common.CityAreaPO;
import com.treasure.mall.biz.entity.embeddable.ReceivingInfo;
import com.treasure.mall.biz.entity.order.BizOrderPO;
import com.treasure.mall.biz.entity.order.RebateBillPO;
import com.treasure.mall.biz.entity.order.SettlementBillPO;
import com.treasure.mall.biz.entity.order.SubOrderPO;
import com.treasure.mall.biz.entity.pay.PaymentBillPO;
import com.treasure.mall.biz.entity.pay.RefundBillPO;
import com.treasure.mall.biz.entity.user.UserPO;
import com.treasure.mall.biz.service.core.BaseConfigService;
import com.treasure.mall.biz.service.core.order.*;
import com.treasure.mall.biz.service.core.pay.PaymentBillService;
import com.treasure.mall.biz.service.core.pay.RefundBillService;
import com.treasure.mall.biz.service.core.user.UserService;
import com.treasure.mall.zbq.common.Jsr310Utils;
import com.treasure.mall.zbq.common.StringUtilsExt;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbq.common.base.ResultCodeEnum;
import com.treasure.mall.zbq.common.constant.Constant;
import com.treasure.mall.zbq.common.ienum.ExpressCompany;
import com.treasure.mall.zbq.common.ienum.order.OrderEnums;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/6/11
 */
@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private SubOrderService orderService;
    @Autowired
    private DealOrderService dealOrderService;
    @Autowired
    private BizOrderService bizOrderService;
    @Autowired
    private PaymentBillService paymentBillService;
    @Autowired
    private RefundBillService refundBillService;
    @Autowired
    private DeliverService deliverService;
    @Autowired
    private BaseConfigService baseConfigService;
    @Autowired
    private RebateBillService rebateBillService;
    @Autowired
    private SettlementBillService settlementBillService;
    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public String list(
            @ModelAttribute("condition") OrderSearchCondition condition,
            @RequestParam(required = false, defaultValue = "1") int pageIndex,
            Model model
    ) {

        if (StringUtils.isNotBlank(condition.getParentMobile())) {
            UserPO parentUser = userService.findByUsername(condition.getParentMobile());
            if (parentUser != null) {
                condition.setParentId(parentUser.getId());
            }
        }

        Page<SubOrderPO> orderPOS = orderService.findAll(pageIndex, Constant.DEFAULT_PAGE_SIZE, condition);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalRecords", orderPOS.getTotalElements());
        model.addAttribute("totalPages", orderPOS.getTotalPages());
        model.addAttribute("orders", orderPOS.getContent());
        model.addAttribute("deliverStatuses", OrderEnums.DeliverStatus.values());

        return "order/order_list";
    }

    @GetMapping("/export")
    public void export(
            OrderSearchCondition condition,
            @RequestParam(required = false, defaultValue = "1") int beginPage,
            int pageCount,
            HttpServletResponse response
    ) throws IOException {
        if (StringUtils.isNotBlank(condition.getParentMobile())) {
            UserPO parentUser = userService.findByUsername(condition.getParentMobile());
            if (parentUser != null) {
                condition.setParentId(parentUser.getId());
            }
        }


        HSSFWorkbook workbook = orderService.export(beginPage, pageCount, condition);

        try (OutputStream output = response.getOutputStream()) {
            response.reset();
            response.setHeader("Content-disposition", "attachment; filename=order_list_"
                    + Jsr310Utils.DateTime.asString(LocalDateTime.now(), StringUtilsExt.TIME_PATTERN_WITH_NO_SEG) + ".xls");
            response.setContentType("application/msexcel");
            workbook.write(output);
            output.flush();
        }
    }

    @GetMapping("/detail")
    public String detail(String orderId, Model model) {
        SubOrderPO orderPO = orderService.findById(orderId);
        model.addAttribute("order", orderPO);

        return "order/order_detail";
    }

    /**
     * 佣金
     *
     * @param orderItemId
     * @return
     */
    @GetMapping("/detail/rebates")
    public String paymentList(@ModelAttribute("orderItemId") Long orderItemId, Model model) {
        List<RebateBillPO> pos = rebateBillService.findByOrderItem(orderItemId);

        model.addAttribute("list", pos);
        return "order/rebate_list";
    }

    /**
     * 结算货款列表
     *
     * @return
     */
    @GetMapping("/detail/settlements")
    public String settlements(@ModelAttribute("orderItemId") Long orderItemId, Model model) {
        SettlementBillPO po = settlementBillService.findByOrderItem(orderItemId);

        model.addAttribute("item", po);

        return "order/settlement_list";
    }

    /**
     * 收款单
     *
     * @return
     */
    @GetMapping("/detail/payments")
    public String payments(String orderId, Model model) {
        SubOrderPO subOrderPO = orderService.findById(orderId);
        model.addAttribute("order", subOrderPO);
        List<PaymentBillPO> paymentBillPOS = paymentBillService.findByOrder(subOrderPO.getOrderPO().getOrderId());
        model.addAttribute("payments", paymentBillPOS);
        List<RefundBillPO> refundBillPOS = refundBillService.findByOrder(orderId);
        model.addAttribute("refunds", refundBillPOS);

        return "order/order_detail_payments";
    }

    @GetMapping("/detail/deliver")
    public String deliver(String orderId, Model model) {
        model.addAttribute("order", orderService.findById(orderId));
        model.addAttribute("bills", deliverService.findByOrder(orderId));

        return "order/order_detail_deliver";
    }

    @GetMapping("/deliver")
    public String toDeliver(String orderId, Model model) {
        SubOrderPO orderPO = orderService.findById(orderId);
        model.addAttribute("order", orderPO);
        model.addAttribute("expressCompanies", ExpressCompany.values());

        return "order/deliver";
    }

    @PostMapping("/deliver")
    @ResponseBody
    public ApiResult deliver(DeliverDTO deliverDTO, @AuthenticationPrincipal UserDetails userDetails) {
        orderService.deliver(deliverDTO, userDetails);

        return ApiResult.resultWith(ResultCodeEnum.SUCCESS);
    }

    @PostMapping("/receive")
    @ResponseBody
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResult receive(String subOrderId) {
        deliverService.receiveByUser(subOrderId);

        return ApiResult.ok();
    }

    @PostMapping("/settled")
    @ResponseBody
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResult settled(String subOrderId) {
        orderService.convert(subOrderId);

        return ApiResult.ok();
    }

    /**
     * 业务订单列表
     *
     * @param condition
     * @param pageIndex
     * @param model
     * @return
     */
    @GetMapping("/biz/list")
    public String bizOrders(
            @ModelAttribute("condition") BizOrderCondition condition,
            @RequestParam(required = false, defaultValue = "1") int pageIndex,
            Model model
    ) {
        Page<BizOrderPO> orderPOS = bizOrderService.findAll(pageIndex, Constant.DEFAULT_PAGE_SIZE, condition);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalRecords", orderPOS.getTotalElements());
        model.addAttribute("totalPages", orderPOS.getTotalPages());
        model.addAttribute("orders", orderPOS.getContent());

        return "order/biz_order_list";
    }


    /**
     * 获取行政区域
     *
     * @param pid
     * @return
     */
    @GetMapping("/cities")
    @ResponseBody
    public ApiResult cities(@RequestParam(required = false, defaultValue = "0") int pid) {
        List<CityAreaPO> cityAreaPOS = baseConfigService.getCities(pid);
        return ApiResult.ok(cityAreaPOS);
    }

    /**
     * 修改订单收货地址
     *
     * @param orderId
     * @param receivingInfo
     * @return
     */
    @PostMapping("/update/shipAddress")
    @ResponseBody
    public ApiResult updateOrderShipAddress(String orderId, ReceivingInfo receivingInfo) {
        dealOrderService.updateOrderShipInfoByOrderId(orderId, receivingInfo);
        return ApiResult.ok();
    }


}
